<?php

use Core\CashierController;
use Models\Order;
use Models\Order_item;
use Models\Item;
use Models\Pending_order;
use Models\Address;
use Models\User;
use Models\UserLevel;
use Models\Cashier;
use Models\OrderRefund;
use Models\Refund;
use Models\Recharge;
use Models\Money_log;
use Models\PurchaseRecord;
use Models\Damage;
use Models\Product;

class OrderController extends CashierController
{


    /**
     * 挂单
     * @method POST
     */
    public function bill()
    {
        $data['privilege'] = floatval($this->input->post('privilege')) ?: 0.00; //优惠金额
        $data['user_id'] = $this->input->post('user_id'); //用户ID
        $data['remark'] = $this->input->post('remark'); //备注
        $data['items'] = $this->input->post('items'); //商品规格ID
        $data['numbers'] = $this->input->post('numbers'); //数量
        $data['cashier_id'] = $this->session->cashier['id'];
        $data['create_time'] = date('Y-m-d H:i:s');
        if (!$data['items'] || !$data['numbers']) {
            $this->error();
        }

        $pending_order = new Pending_order;
        $order_id = $pending_order->add($data);
        return $this->success();
    }

    /**
     * 获取挂单订单
     * @method GET
     */
    public function get_bills()
    {
        $pending_order = new Pending_order;
        $orders = $pending_order->order_by('id', 'desc')->paginate(6);

        $item_ids = array();
        $user_ids = array();
        foreach ($orders as $o) {
            $item_ids = array_merge($item_ids, explode(',', $o['items']));
            if ($o['user_id']) {
                $user_ids[] = $o['user_id'];
            }
        }

        //查找商品
        if (!empty($item_ids)) {
            $item = new Item;
            $items = $item->select('items.*,products.title as p_title,products.en_title as p_en_title, products.thumbnail,products.unit')
            ->join('products', 'products.id=items.product_id')
            ->where_in('items.id', $item_ids)
            ->default_filter(false)->get();
            $items = arr_key($items);
        }

        //查找用户
        if (!empty($user_ids)) {
            $user = new User;
            $users = $user->select('id,phone,cashier_id,first_name,last_name,nickname,avatar,balance,level')->with('level')->where_in('id', $user_ids)->get();
            $users = arr_key($users);
        }


        $orders = $orders->to_array();
        foreach ($orders['data'] as $k => $o) {
            if (!empty($user_ids) && isset($users[$o['user_id']])) {
                $orders['data'][$k]['user'] = $users[$o['user_id']];
            }

            $its = explode(',', $o['items']);
            $nums = explode(',', $o['numbers']);
            $new_arr = array();
            $i = 0;
            foreach ($its as $it) {
                $new_arr[] = ['id'=>$it,'qty'=>$nums[$i]];
                $i++;
            }
            $total_number = 0; //总商品数量
            $total_fee = 0; //总金额
            $item_arr = array_map(function ($ar) use ($items, &$total_number, &$total_fee) {
                if (isset($items[$ar['id']])) {
                    $itm = $items[$ar['id']];
                    $itm['qty'] = $ar['qty'];
                    $total_number += $ar['qty'];
                    $total_fee += $itm['price']*$ar['qty'];
                    return $itm;
                }
            }, $new_arr);

            $orders['data'][$k]['items'] = $item_arr;
            $orders['data'][$k]['total_number'] = $total_number;
            $orders['data'][$k]['total_fee'] = $total_fee;
        }

        $this->success($orders);
    }

    /**
     * 删除挂单
     * @return JSON
     */
    public function delete_bill()
    {
        $id = intval($this->input->post('id'));
        $pending_order = (new Pending_order)->find($id);
        if (!$id) {
            return $this->error();
        }
        $pending_order->delete($id);
        return $this->success();
    }

    /**
     * 获取单个挂单数据
     * @param  int $id 挂单ID
     * @return JSON
     */
    public function get_bill($id)
    {
        $pending_order = (new Pending_order)->find($id);
        if (!$pending_order) {
            return $this->error('404');
        }
        //查找商品
        $item = new Item;
        $items = $item->select('items.*,products.title as p_title,products.en_title as p_en_title, products.thumbnail,products.unit')
            ->join('products', 'products.id=items.product_id')
            ->where_in('items.id', explode(',', $pending_order['items']))
            ->default_filter(false)->get();
        $items = arr_key($items);

        //查找用户
        if ($pending_order['user_id']) {
            $data['user'] = (new User)->select('id,first_name,last_name,nickname,phone,avatar,balance,level')->find($pending_order['user_id']);
            if ($data['user']) {
                $address = (new Address)->where('user_id', $data['user']['id'])->get_one();
                $data['user']['address'] = $address ? $address->region($address['id'])['address'] : '';
                $data['user']['zip'] = $address ? $address['zip'] : '';
                $data['level'] = $data['user']->level();
            }
        }

        $its = explode(',', $pending_order['items']);
        $nums = explode(',', $pending_order['numbers']);
        $new_arr = array();
        $i = 0;
        foreach ($its as $it) {
            $new_arr[] = ['id'=>$it,'qty'=>$nums[$i]];
            $i++;
        }
        $total_number = 0; //总商品数量
        $total_fee = 0; //总金额
        $item_arr = array_map(function ($ar) use ($items, &$total_number, &$total_fee) {
            if (isset($items[$ar['id']])) {
                $itm = $items[$ar['id']];
                $itm['qty'] = $ar['qty'];
                $total_number += $ar['qty'];
                $total_fee += $itm['price']*$ar['qty'];
                return $itm;
            }
        }, $new_arr);

        $data['items'] = $item_arr;
        $data['total_number'] = $total_number;
        $data['total_fee'] = $total_fee;
        $data['privilege'] = $pending_order['privilege'];
        $data['remark'] = $pending_order['remark'];

        //删除挂单
        $pending_order->delete();

        return $this->success($data);
    }


    // 创建订单
    // 返回http status
    // 500=>商品和数量填写不正确
    // 422=>创建订单失败
    // 200=>成功，返回order_id(订单ID)和fee(需要支付的金额)
    public function create()
    {
        $options['type'] = 1;
        $options['cut_fee'] = floatval($this->input->post('privilege')) ?: 0.00; //优惠金额
        $user_id = $this->input->post('user_id'); //用户ID
        $options['remark'] = $this->input->post('remark'); //备注
        $options['cashier_id'] = $this->session->cashier['id'];
        $options['address_id'] = 0;

        $items = $this->input->post('items'); //商品规格ID
        $qtys = $this->input->post('numbers'); //数量
        if (!$items || !$qtys) {
            $this->error();
        }

        $items = explode(',', $items);
        $qtys = explode(',', $qtys);

        $data = array();
        $i = 0;
        foreach ($items as $it) {
            $data[] = array('item_id'=>$it,'qty'=>$qtys[$i]);
            $i++;
        }


        $order = new Order;
        $result = $order->create($data, $user_id, $options);
        if (!$result) {
            $error = $order->error_info[$order->error];
            return $this->validateError($error);
        }

        $this->success(['options'=>$options,'order_id'=>$result['id'],'fee'=>$result['total']-$result['cut_fee']]);
    }

    // 支付订单
    // 返回http status
    // 500[404]=>订单未找到
    public function pay()
    {
        $order_id = $this->input->post('order_id');
        $order = (new Order)->find($order_id);
        if (!$order) {
            return $this->error('404');
        }
        $data = array();
        $pay_mode = $this->input->post('pay_mode'); //支付方式
        $pay_fee = $this->input->post('pay_fee'); //支付的金额
        $modes = explode(',', $pay_mode);
        $money_pay = 0; //是否使用会员卡支付
        $pay_mode = 0; //其他支付方式
        if (count($modes)>1) {
            $pay_mode = $modes[0];
            $money_pay = 1;
        } else {
            if ($modes[0] == 0) {
                $money_pay = 1;
                // 判断余额是否足够
                $user = (new User)->find($order['user_id']);
                if ($user['balance'] < $order['total'] + $order['shipping_fee'] - $order['cut_fee']) {
                    return $this->error('账户余额不足');
                }
            } else {
                $pay_mode = $modes[0];
            }
        }

        if (in_array(0, $modes)) {
            $user = (new User)->find($order['user_id']);
            if ($user['pay_pass'] && $user['pay_pass'] != $this->input->post('pay_pass')) {
                return $this->error('支付密码错误');
            }
        }

        $result = $order->payed($order, $money_pay, $pay_mode, $pay_fee, '', 1);
        if ($result === true) {
            $order->purchaseRecordStock($order_id);

            // 计算vat 价格
            $order = $order->find($order['id']);
            return $this->success([
                'id' => $order['order_id'],
                'vat' => $order['vat']
            ]);
        } else {
            return $this->error($result['code']);
        }
    }

    /**
     * 查找订单
     */
    public function get_orders()
    {
        $cashier_id = $this->session->cashier['id'];
        $date = $this->input->get('date');
        $keyword = $this->input->get('keyword');
        $is_my = $this->input->get('is_my');
        $order = new Order;
        $order->select('orders.*,users.first_name,users.last_name,users.nickname,users.avatar,users.balance,users.phone, users.balance, cashiers.username as cashier_name');
        if ($is_my) {
            $order->group_start()
                ->where('orders.cashier_id', $cashier_id)
                ->or_where('orders.type', 0)
            ->group_end();
        }
        $order->where(['orders.status>='=>2,'orders.status<'=>8]);
        $order->join('users', 'users.id=orders.user_id', 'left');
        $order->join('cashiers', 'cashiers.id=orders.cashier_id', 'left');
        if ($date) {
            $arr = [
                'orders.create_time >='=>$date.' 00:00:00',
                'orders.create_time <='=>$date.' 23:59:59',
            ];
            $order->where($arr);
        }
        if ($keyword) {
            $order->group_start();
            $order->like('orders.order_id', $keyword);
            $order->or_where('orders.id', $keyword);
            $order->or_like('users.phone', $keyword);
            $order->group_end();
        }

        $orders = $order->order_by("orders.id", 'desc')->paginate(10);
        if ($this->input->get('d')) {
            $this->output->enable_profiler(true);
        } else {
            $this->success($orders->to_array());
        }
    }

    /**
     * 获取单个订单信息
     * @param  int $id 订单ID
     * @return JSON 500[404=>未找到订单]
     *
     */
    public function get_order($id)
    {
        $order = (new Order)->where('id', $id)->or_where('order_id', $id)->get_one();
        if (!$order) {
            return $this->error('404');
        }
        $order['address'] = $order->address();
        if ($order['cashier_id']) {
            $data['cashier'] = (new Cashier)->find($order['cashier_id']);
        }
        $data['items'] = (new Order_item)->where('order_id', $order['id'])
                                 ->with('product', 'id,thumbnail,title,en_title,unit')
                                 ->with('item', 'id,en_title,title,price,tax as vat')
                                 ->default_filter(false)
                                 ->get();
        $data['order'] = $order;
        $data['order_refund'] = $order->order_refund();
        $data['order_refund'] = $data['order_refund'] ?: null;

        $data['refunds'] = (new Refund)
            ->default_filter(false)
            ->with([
                'item' => function ($q) {
                    $q->select('id, product_id, title, en_title, price, tax')->with([
                        'product' => function ($q) {
                            $q->select('id, title, en_title');
                        }
                    ]);
                }
            ])
            ->where('order_id', $order['id'])
            ->get();
        $data['refunds'] = array_map(function ($item) {
            $item['title'] = $item['item']['product']['title'].' '.$item['item']['title'];
            $item['price'] = $item['item']['price'];
            $item['vat'] = $item['item']['tax'] * $item['qty'];

            unset($item['item']);
            return $item;
        }, $data['refunds']);

        $data['user'] = (new User)->find($order['user_id']);

        return $this->success($data);
    }

    /**
     * 退换货列表
     * @return JSON
     */
    public function get_refunds()
    {
        $order_refund = new OrderRefund();
        $order_refund->with([
            'user' => function ($query) {
                $query->select('id, first_name, last_name, balance');
            },
            'cashier' => function ($query) {
                $query->select('id, username');
            },
            'order' => function ($query) {
                $query->select('id, order_id');
            }
        ])
        ->where([
                'cashier_id' => $this->session->cashier['id'],
                'status' => 3
            ]);
        if ($this->input->get('date')) {
            $order_refund->where([
                'create_time >='=>$this->input->get('date').' 00:00:00',
                'create_time <='=>$this->input->get('date').' 23:59:59',
            ]);
        }
        if ($this->input->get('keyword')) {
            $order = Order::where('order_id', $this->input->get('keyword'))->get_one();
            $user = User::where('phone', $this->input->get('keyword'))->get_one();
            $order_refund->group_start();
            $order_refund->where('order_id', $order['id']);
            if ($user) {
                $order_refund->or_where('user_id', $user['id']);
            } else {
                $order_refund->or_where('user_id', -1);
            }
            $order_refund->group_end();
        }

        $refunds = $order_refund->order_by('id desc')->paginate(10)->to_array();

        $refunds['data'] = array_map(function ($item) {
            $item['first_name'] = !empty($item['user']) ? $item['user']['first_name'] : '';
            $item['last_name'] = !empty($item['user']) ? $item['user']['last_name'] : '';
            $item['balance'] = !empty($item['user']) ? $item['user']['balance'] : 0.0;
            $item['cashier_name'] = !empty($item['cashier']) ? $item['cashier']['username'] : '';

            return $item;
        }, $refunds['data']);

        return $this->success($refunds);
    }

    /**
     * 退换货
     * @return JSON
     */
    public function refund()
    {
        $data['order_id'] = $this->input->post('order_id');
        $data['pay_mode'] = $this->input->post('pay_mode');
        $data['remark'] = $this->input->post('remark');
        $data['status'] = 3;
        $data['cashier_id'] = $this->session->cashier['id'];
        $data['create_time'] = date('Y-m-d H:i:s');

        $order_item_id = $this->input->post('order_item_id');
        $product_id = $this->input->post('product_id');
        $item_id = $this->input->post('item_id');
        $qty = $this->input->post('qty');
        $money = $this->input->post('money');
        $reason = $this->input->post('reason');
        $type = $this->input->post('type');
        $is_damaged = $this->input->post('is_damaged');
        $order = (new Order)->or_where([
            'order_id' => $data['order_id'],
            'id' => $data['order_id']
            ])->get_one();
        $user = (new User)->find($order['user_id']);

        $order_refund = new OrderRefund;
        $order_refund->load([
            'order_id' => $this->input->post('order_id'),
            'user_id' => $order['user_id'],
            'cashier_id' => $this->session->cashier['id'],
            'pay_mode' => $this->input->post('pay_mode'),
            'create_time' => date('Y-m-d H:i:s'),
            'remark' => $data['remark'],
            'status' => 3
        ]);
        $order_refund['id'] = $order_refund->add();
        $data['order_refund_id'] = $order_refund['id'];

        $i = 0;
        $total_money = 0;
        $vat = 0;
        $product_ids = [];
        foreach ($order_item_id as $oid) {
            $data['order_item_id'] = $oid;
            $data['product_id'] = $product_id[$i];
            $data['item_id'] = $item_id[$i];
            $data['qty'] = $qty[$i];
            $data['money'] = $money[$i];
            $data['reason'] = $reason[$i];
            $data['type'] = $type[$i];
            $data['is_damaged'] = $is_damaged[$i];
            $total_money += $data['money'];
            $i++;
            $refund = (new Refund)->add($data);
            $refund = (new Refund)->find($refund);


            if ($data['type'] == 0) {
                //如果是退货
                (new Order_item)->increment('refund_qty', $oid, $data['qty']);
                if ($data['is_damaged'] == 0) {
                    //普通退货情况下，添加商品库存,添加进货记录库存量
                    (new Item)->increment('stock', $data['item_id'], $data['qty']);
                    (new PurchaseRecord)->stock($data['item_id'], $data['qty']);
                }
                //减少商品销售数量
                (new Item)->decrement('solded', $data['item_id'], $data['qty']);
            }

            if ($data['is_damaged'] == 1) {
                $order_refund['is_damaged'] = 1;
                //货损，减少商品库存，减少进货记录库存
                (new Item)->decrement('stock', $data['item_id'], $data['qty']);
                (new PurchaseRecord)->stock($data['item_id'], -$data['qty']);

                $damage_data['type'] = $data['reason'] == '商品过期'?1:0;
                $damage_data['product_id'] = $data['product_id'];
                $damage_data['item_id'] = $data['item_id'];
                $damage_data['cashier_id'] = $data['cashier_id'];
                $damage_data['qty'] = $data['qty'];
                $damage_data['create_time'] = $data['create_time'];
                (new Damage)->add($damage_data);
            }

            if ($data['type'] == 0 || $data['is_damaged'] == 1) {
                if (!in_array($data['product_id'], $product_ids)) {
                    $product_ids[] = $data['product_id'];
                }
            }

            if ($data['type'] == 0) {
                $item = (new Item)->find($data['item_id']);
                $vat += $item['tax'] * $data['qty'];
            }
        }

        //换货的情况下，减少商品库存
        if (!empty($product_ids)) {
            (new Product)->stock($product_ids);
        }

        //订单中添加退款金额
        if ($total_money>0) {
            (new Order)->increment('refund_fee', $data['order_id'], $total_money);
            if ($user) {
                $user->update($user['id'], [
                    'balance' => $user['balance'] + $total_money
                ]);
            }
        }

        // 保存退货单
        $order_refund['money'] = $total_money;
        $order_refund['last'] = isset($user) ? $user['balance'] : 0;
        $order_refund['now'] = isset($user) ? $user['balance'] + $total_money : 0;
        $order_refund['vat'] = $vat;
        $order_refund->update();
        $order_refund->saveMoneyLog([
            'desc' => $order['order_id'],
            'from' => 'cashier',
        ]);

        //将订单设置为有退换货情况
        (new Order)->update($data['order_id'], ['have_refund'=>1]);

        $refunds = (new Refund)
            ->default_filter(false)
            ->with([
                'item' => function ($q) {
                    $q->select('id, product_id, title, en_title, price, tax')->with([
                        'product' => function ($q) {
                            $q->select('id, title, en_title');
                        }
                    ]);
                }
            ])
            ->where('order_id', $order['id'])
            ->get();
        $data['refunds'] = array_map(function ($item) {
            $item['title'] = $item['item']['product']['title'].' '.$item['item']['title'];
            $item['price'] = $item['item']['price'];
            $item['vat'] = $item['item']['tax'] * $item['qty'];

            unset($item['item']);
            return $item;
        }, $refunds);

        $this->success([
                'order_refund' => $order_refund,
                'refunds' => $data['refunds'],
            ]);
    }

    /**
     * 会员充值记录
     */
    public function get_users()
    {
        $money_log = new Money_log;

        if ($this->input->get('date')) {
            $arr = [
                'money_logs.create_time >='=>$this->input->get('date').' 00:00:00',
                'money_logs.create_time <='=>$this->input->get('date').' 23:59:59',
            ];
            $money_log->where($arr);
        } else {
            // 上班时间的数据
            $log = $this->db->where('cashier_id', $this->session->cashier['id'])->order_by('id desc')->get('cashier_login_logs')->row_array();
            $money_log->where([
                'money_logs.create_time >=' => $log['login_time']
            ]);
        }

        $money_log->select('money_logs.*,users.first_name,users.last_name,users.phone,users.nickname,users.level,users.avatar,users.balance,users.wechat,address.address,address.zip,users.email,users.update_at')
            ->join('users', 'users.id=money_logs.user_id', 'left')
            ->join('address', 'address.user_id=users.id', 'left');
        $money_log->where('money_logs.cashier_id', $this->session->cashier['id'])->where('money_logs.type', 3);

        if ($this->input->get('keyword')) {
            $money_log->like('users.phone', $this->input->get('keyword'));
        }
        $money_logs = $money_log
            ->with('cashier')
            ->order_by('id desc')->paginate(10);
        $data = $money_logs->to_array();
        $data['data'] = array_map(function ($item) {
            $last = (new Money_log)->where('user_id', $item['user_id'])->order_by('id desc')->get_one();

            $item['order_id'] = $last ? $last['relation_id'] : '';
            $item['order_last'] = $last ? $last['create_time'] : '';
            $item['cashier_name'] = $item['cashier'] ? $item['cashier']['username'] : '';

            return $item;
        }, $data['data']);

        return $this->success($data);
    }

    public function get_recharge()
    {
        // 上班时间的数据
        $log = $this->db->where('cashier_id', $this->session->cashier['id'])->order_by('id desc')->get('cashier_login_logs')->row_array();



        $money_log = new Money_log;
        if ($this->input->get('keyword')) {
            $user = (new User)->where('phone', $this->input->get('keyword'))->get_one();
            $money_log->where('user_id', $user ? $user['id'] : -1);
        } elseif ($this->input->get('date')) {
            $arr = [
                'create_time >='=>$this->input->get('date').' 00:00:00',
                'create_time <='=>$this->input->get('date').' 23:59:59',
            ];
            $money_log->where($arr);
        } else {
            $money_log->where([
                'create_time >=' => $log['login_time']
            ]);
        }

        $money_logs = $money_log->where_in('type', [2,3])
                ->with([
                    'user' => function ($db) {
                        $db->select('id,first_name,last_name,phone');
                    },
                    'cashier' => function ($db) {
                        $db->select('id, username');
                    },
                    'recharge',
                ])
                ->order_by('id desc')
                ->paginate(10)
                ->to_array();
        ;

        $money_logs['data'] = array_map(function ($item) {
            $item['num'] = $item['recharge']['money'];
            return array_merge($item['user'], ['cashier_name' => $item['cashier']['username']], $item);
        }, $money_logs['data']);

        return $this->success($money_logs);
    }

    public function get_xiaofei()
    {
        // 上班时间的数据
        $log = $this->db->where('cashier_id', $this->session->cashier['id'])->order_by('id desc')->get('cashier_login_logs')->row_array();
        $money_log = new Money_log;
        $money_log->select('money_logs.*,users.first_name,users.last_name,users.phone,users.balance,cashiers.username as cashier_name, orders.have_refund')
            ->join('users', 'users.id=money_logs.user_id', 'left')
            ->join('cashiers', 'cashiers.id=money_logs.cashier_id', 'left')
            ->join('orders', 'orders.id=money_logs.relation_id', 'left')
            ->where('money_logs.user_id !=', 0)
            ->where_in('money_logs.type', [0,1,4]);

        if ($this->input->get('keyword')) {
            $money_log->like('users.phone', $this->input->get('keyword'));
        } elseif ($this->input->get('date')) {
            $date = new DateTime($this->input->get('date'));
            $money_log->where([
                'money_logs.create_time >=' => $date->format('Y-m-d 00:00:00'),
                'money_logs.create_time <=' => $date->format('Y-m-d 23:59:59')
            ]);
        } else {
            $money_log->where([
                'money_logs.create_time >=' => $log['login_time'] > date('Y-m-d 00:00:00') ? date('Y-m-d 00:00:00') : $log['login_time']
            ]);
        }

        $money_logs = $money_log->order_by('id desc')->paginate(10);

        return $this->success($money_logs->to_array());
    }

    /**
     * 交班
     * @return JSON
     */
    public function exchange()
    {
        $cashier_id = $this->session->cashier['id'];
        $cashier = (new Cashier)->findOrFail($cashier_id);
        $last_login = $cashier->last_login();

        $arr = [
            'create_time >='=>$last_login['login_time'] ?: date('Y-m-d 00:00:00'),
            'create_time <='=>date('Y-m-d H:i:s'),
        ];
        $money_log = new Money_log;

        //会员充值金额
        $charge_money = $money_log->select_sum('num')->where(['cashier_id'=>$cashier_id,'type'=>3])->where($arr)->get();
        $charge_money = $charge_money[0]['num'];
        //新增会员金额
        $reg_money = $money_log->select_sum('num')->where(['cashier_id'=>$cashier_id,'type'=>3,'last'=>0])->where($arr)->get();
        $reg_money = $reg_money[0]['num'];

        //新增会员人数
        $reg_user = (new User)->where(['cashier_id'=>$cashier_id])->where([
            'create_at >='=>$last_login['login_time'] ?: date('Y-m-d 00:00:00'),
            'create_at <='=>date('Y-m-d H:i:s')
        ])->counts();

        //充值会员人数
        $charge_user = count($money_log->select('id')->where(['cashier_id'=>$cashier_id,'type'=>3])->where($arr)->group_by('user_id')->get());

        $data['user'] = [
            'reg_user'=>$reg_user, //新增会员人数
            'charge_user'=>$charge_user, //充值会员人数
            'reg_money'=>$reg_money, //新增会员金额
            'charge_money'=>$charge_money, //充值金额
            'user_total_money'=>$reg_money + $charge_money, //总充值金额
        ];


        //订单总金额，实收金额
        $order = new Order;
        $orders = $order->select_sum('total')->select_sum('cut_fee')->where(['cashier_id'=>$cashier_id,'status>'=>2,'status<'=>8])->where($arr)->get();
        $order_total = $orders[0]['total'];
        $order_cut_fee = $orders[0]['cut_fee'];
        //订单数
        $order_counts = $order->where(['cashier_id'=>$cashier_id,'status>'=>2,'status<'=>8])->where($arr)->counts();
        $item_counts = (new Order_item)->select_sum('order_items.qty')->join('orders', 'orders.id = order_items.order_id')->where(['cashier_id'=>$cashier_id,'orders.status>'=>2,'orders.status<'=>8])->where($arr)->get();
        $item_counts = $item_counts[0]['qty'];
        //现金收入
        $cash = $money_log->select('abs(sum(num)) as num')->where(['cashier_id'=>$cashier_id,'pay_type'=>1])->where($arr)->get();
        $cash = $cash[0]['num'];

        $order_other = $order_total - $order_cut_fee - $cash;

        $data['order'] = [
            'order_counts'=>$order_counts, //成交单数
            'order_items'=>$item_counts, //商品总数
            'order_total'=>$order_total, //销售总额
            'order_cut_fee'=>$order_cut_fee, //优惠总额
            'order_money'=>$order_total - $order_cut_fee, //实际收入
            'order_cash'=>$cash, //现金收入
            'order_other'=>$order_other > 0 ? $order_other : 0 //其他
        ];

        //退换货
        $refund = new Refund;
        //退款总金额
        $refunds = $refund->where(['cashier_id'=>$cashier_id,'status'=>3])->where($arr)->get();

        //退货单数
        $refund_tui = 0; //退货商品数
        $refund_huan = 0; //换货商品数
        $refund_mony = 0; //退货金额
        $refund_damaged = 0; //货损数量
        $refund_cash = 0; //现金退款金额
        $refund_orders = [];
        foreach ($refunds as $r) {
            if (!in_array($r['order_id'], $refund_orders)) {
                $refund_orders[] = $r['order_id'];
            }
            if (!$r['type']) {
                $refund_tui += $r['qty'];
            } else {
                $refund_huan += $r['qty'];
            }
            $refund_mony += $r['money'];
            if ($r['is_damaged']) {
                $refund_damaged += $r['qty'];
            }
            if ($r['pay_mode'] == 1) {
                $refund_cash += $r['money'];
            }
        }

        $data['refund'] = [
            'refund_orders'=>count($refund_orders), //退换货单数
            'refund_tui'=>$refund_tui, //退货商品数
            'refund_huan'=>$refund_huan,//换货商品数
            'refund_damaged'=>$refund_damaged, //货损数量
            'refund_mony'=>$refund_mony,//合计退款
            'refund_cash'=>$refund_cash,//现金退款
            'refund_balance'=>$refund_mony - $refund_cash, //余额退款
        ];
        $data = array_merge($data['order'], $data['user'], $data['refund']);

        foreach ($data as $key => $value) {
            if (!$value) {
                $data[$key] = 0;
            }
        }

        $this->success($data);
    }
}
